package com.timu.filter;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.timu.bean.RequestMsg;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.util.stream.Collectors;

@WebFilter(filterName="firstFilter", urlPatterns="/webhook/v2")
public class WebhookFilter implements Filter {
 
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("helloworld");
	}
 
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpRequest= (HttpServletRequest) request;
		ServletRequest requestWrapper=null;
		if (request instanceof HttpServletRequest){
			requestWrapper=new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
		}

		String path = httpRequest.getRequestURI();
		//fe使用gson,这里使用fastjson
		Gson gson = new Gson();
		String body = requestWrapper.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
		RequestMsg requestBody= JSON.parseObject(body,RequestMsg.class);
		System.out.println(requestBody);
		String action = requestBody.getAction();
		if (action!=null&&action!=""){
			String contextPath=path+"/"+action;
			requestWrapper.getRequestDispatcher(contextPath.replace("/isp_fe","")).forward(requestWrapper,response);
		}
	}
 
	@Override
	public void destroy() {
		
	}

	static class  BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
		private final byte[] body;

		/**
		 * Constructs a request object wrapping the given request.
		 *
		 * @param request The request to wrap
		 * @throws IllegalArgumentException if the request is null
		 */
		public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
			super(request);
			body=toByteArray(request.getInputStream());
		}

		private byte[] toByteArray(InputStream in) throws IOException{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer=new byte[1024*4];
			int n=0;
			while ((n=in.read(buffer))!=-1){
				out.write(buffer,0,n);
			}
			return out.toByteArray();

		}

		@Override
		public BufferedReader getReader() throws IOException {
			return new BufferedReader(new InputStreamReader(getInputStream()));
		}

		@Override
		public ServletInputStream getInputStream() throws IOException {
			final ByteArrayInputStream bais=new ByteArrayInputStream(body);
			return new ServletInputStream() {
				@Override
				public boolean isFinished() {
					return false;
				}

				@Override
				public boolean isReady() {
					return false;
				}

				@Override
				public void setReadListener(ReadListener readListener) {

				}

				@Override
				public int read() throws IOException {
					return bais.read();

				}
			};
		}
	}
}